import Note from '@/apis/notes.js'
import { Message } from 'element-ui'
const store = {
  // data
  state: {
    notes: null,
    curNoteId: null,
  },
  //计算属性 computed
  getters: {
    notes: (state) => state.notes || [],
    curNote: (state) => {
      if (!Array.isArray(state.notes)) return {}
      if (!state.curNoteId) return state.notes[0] || {}
      return state.notes.find((note) => note.id == state.curNoteId) || {}
    },
  },

  // 方法 methods 不能操作异步函数
  mutations: {
    setNote(state, payload) {
      state.notes = payload.notes
    },

    addNote(state, payload) {
      state.notes.unshift(payload.note)
    },

    updateNote(state, payload) {
      let note = state.notes.find((note) => note.id === payload.noteId) || {}
      note.title = payload.title
      note.content = payload.content
    },

    deleteNote(state, payload) {
      state.notes = state.notes.filter((note) => note.id !== payload.noteId)
    },
    setCurNote(state, payload = {}) {
      state.curNoteId = payload.curNoteId
    },
  },

  //Action 类似于 mutation，不同在于：Action 提交的是 mutation，而不是直接变更状态 Action 可以包含任意异步操作
  actions: {
    getNotes({ commit }, { notebookId }) {
      return Note.getAll({
        notebookId,
      }).then((res) => {
        commit('setNote', {
          notes: res.data,
        })
      })
    },

    updateNote({ commit }, { noteId, title, content }) {
      return Note.updateNote(
        {
          noteId,
        },
        {
          title,
          content,
        }
      ).then((res) => {
        commit('updateNote', {
          noteId,
          title,
          content,
        })
      })
    },

    deleteNote({ commit }, { noteId }) {
      return Note.deleteNote({
        noteId,
      }).then((res) => {
        commit('deleteNote', {
          noteId,
        })
        Message({
          type: 'success',
          message: res.msg,
        })
      })
    },

    // 创建笔记本
    addNote({ commit }, { notebookId, title, content }) {
      return Note.addNote(
        {
          notebookId,
        },
        {
          title,
          content,
        }
      ).then((res) => {
        commit('addNote', {
          note: res.data,
        })
        Message({
          type: 'success',
          message: res.msg,
        })
      })
    },
  },
}

export default store
